package com.syt.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.syt.enums.PaymentTypeEnum;
import com.syt.enums.RefundStatusEnum;
import com.syt.model.order.OrderInfo;
import com.syt.model.order.PaymentInfo;
import com.syt.model.order.RefundInfo;
import com.syt.order.service.OrderInfoService;
import com.syt.order.service.PaymentInfoService;
import com.syt.order.service.RefundInfoService;
import com.syt.order.service.WeiXinService;
import com.syt.order.utils.ConstantPropertiesUtils;
import com.syt.order.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: xxx
 * @Date: 2023/2/28 19:51
 * @Description:
 */
@Service
public class WeiXinServiceImpl implements WeiXinService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundInfoService refundInfoService;

    /**
     * 微信退款
     *
     * @param orderId
     * @return
     */
    @Override
    public Boolean weiXinRefund(Long orderId) {
        try {
            //获取支付记录信息
            PaymentInfo paymentInfo = paymentInfoService.getPaymentRecords(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            //添加退款记录
            RefundInfo refundInfo = refundInfoService.insertRefundInfo(paymentInfo);
            //判断当前订单数据是否已经退款
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return true;
            }
            //调用微信接口实现退款
            Map<String, String> paramMap = new HashMap<>(8);
            paramMap.put("appid", ConstantPropertiesUtils.APPID);       //公众账号ID
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);   //商户编号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id", paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no", paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no", "tk" + paymentInfo.getOutTradeNo()); //商户退款单号
//       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
//       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");
            paramMap.put("refund_fee", "1");
            String paramXml = null;
            paramXml = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 查询微信支付状态
     *
     * @param orderId
     * @return
     */
    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        try {
            OrderInfo orderInfo = orderInfoService.getOrdersById(orderId);
            //1、封装参数
            Map paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据，转成Map
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("xml转成Map=" + resultMap);
            //4、返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成微信二维码
     *
     * @param orderId
     * @return
     */
    @Transactional
    @Override
    public Map createQRCode(Long orderId) {
        try {
            //现在redis获取有没有订单数据
            Map payMap = (Map) redisTemplate.opsForValue().get(orderId.toString());
            if (payMap != null) {
                return payMap;
            } else {


                //1、获取订单信息
                OrderInfo orderInfo = orderInfoService.getOrdersById(orderId);
                //2、添加微信支付记录
                paymentInfoService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());
                //3、设置参数 调用微信支付生成二维码
                //把参数转换成xml格式，使用商户key进行加密
                //1、设置参数
                Map paramMap = new HashMap();
                paramMap.put("appid", ConstantPropertiesUtils.APPID);
                paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
                paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
                String body = orderInfo.getReserveDate() + "就诊" + orderInfo.getDepname();
                paramMap.put("body", body);
                paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
                //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
                paramMap.put("total_fee", "1");
                paramMap.put("spbill_create_ip", "127.0.0.1");
                paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
                paramMap.put("trade_type", "NATIVE");
                //2、HTTPClient来根据URL访问第三方接口并且传递参数
                HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                //client设置参数
                client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
                client.setHttps(true);
                client.post();
                //3、返回第三方的数据
                String xml = client.getContent();
                Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
                System.out.println("resultMap:" + resultMap);
                //4、封装返回结果集
                Map map = new HashMap<>();
                map.put("orderId", orderId);
                map.put("totalFee", orderInfo.getAmount());
                map.put("resultCode", resultMap.get("result_code"));
                map.put("codeUrl", resultMap.get("code_url")); //二维码地址
                if (null != resultMap.get("result_code")) {
                    //微信支付二维码2小时过期，可采取2小时未支付取消订单
                    redisTemplate.opsForValue().set(orderId.toString(), map, 120, TimeUnit.MINUTES);
                }
                return map;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }

    }
}
